package com.wehealth.three.lib_connect.device.bluetoothdevice.kdevice

import android.annotation.SuppressLint
import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothSocket
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.wehealth.three.lib_connect.device.usbdevice.data.ParseOriginEcgData
import java.io.IOException
import java.io.InputStream
import java.util.UUID

@SuppressLint("MissingPermission")
class ClassicBlueToothHelper(
    val activity: Activity
) : BlueToothHelper(activity) {

    private var deviceList = mutableListOf<BluetoothDevice>()


    private var bindDeviceList = mutableListOf<BluetoothDevice>()

    fun getDeviceList(): MutableList<BluetoothDevice> {
        return deviceList
    }

    /***
     * 查找设备
     */
    override fun discoverDevice() {
        if (btIsoSupport && btIsEnable) {
            bluetoothAdapter.startDiscovery()
            val filter = IntentFilter(BluetoothDevice.ACTION_FOUND)
            filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)
            context.registerReceiver(receiver, filter)

        }

    }

    /***
     * 停止查找设备
     */
    override fun stopDiscoverDevice() {
        context.unregisterReceiver(receiver)
    }


    @SuppressLint("MissingPermission")
    private fun getBindDevices() {
        bluetoothAdapter?.bondedDevices?.forEach { device ->
            if (!bindDeviceList.contains(device)) {
                bindDeviceList.add(device)
            }
        }
    }

    /***
     * 通过名称或者是mac地址获取已绑定的设备
     */
    private fun getBindDevice(mac: String, type: Int): BluetoothDevice {
        return bindDeviceList.filter { it.address == mac }[0]
    }


    private val receiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            when (intent.action) {
                BluetoothDevice.ACTION_FOUND -> {
                    val device: BluetoothDevice? =
                        intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
                    if (device != null && !deviceList.contains(device)) {
                        if (device.name != null && isWeHealthDevice(device.name, false)) {
                            Log.e("tag", "" + device.name)
                            deviceList.add(device)
                        }

                    }
                }

            }
        }
    }

    /***
     * 连接设备
     */
    override fun connectDevice(
        device: BluetoothDevice,
        ecgDataGetListener: ParseOriginEcgData.EcgDataGetListener
    ): LiveData<String> {
        val liveData = MutableLiveData<String>()
        BTConnectThread(bluetoothAdapter, device, liveData, ecgDataGetListener).start()
        return liveData
    }

    @SuppressLint("MissingPermission")
    class BTConnectThread(
        private val bluetoothAdapter: BluetoothAdapter,
        val device: BluetoothDevice,
        val liveData: MutableLiveData<String>,
        ecgDataGetListener: ParseOriginEcgData.EcgDataGetListener
    ) : Thread() {
        companion object {
            const val TAG = "BTConnectThread"
        }

        private val ecgParser24 =
            ParseOriginEcgData(
                ecgDataGetListener
            )

        private val mmBuffer: ByteArray = ByteArray(1024) // mmBuffer store for the stream
        private val BT_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")
        private val mmSocket: BluetoothSocket? by lazy(LazyThreadSafetyMode.NONE) {
            device.createRfcommSocketToServiceRecord(BT_UUID)
        }

        override fun run() {
            super.run()
            //确保连接之前停止蓝牙扫描
            bluetoothAdapter?.cancelDiscovery()
            try {
                mmSocket?.let { socket ->
                    socket.connect()

                    // todo 蓝牙连接成功
                    mmSocket?.inputStream?.let { readData(it) }

                }
            } catch (e: Exception) {
                //todo 蓝牙连接异常
            }

        }

        private fun writeData(bytes: ByteArray) {
            if (mmSocket?.isConnected == true) {
                try {
                    ecgParser24.ecgDataParserInit()
                    mmSocket?.outputStream?.write(bytes)
                } catch (e: IOException) {
                    //todo 写入失败
                    return
                }
                //todo 写入之后的操作
            }
        }

        private fun readData(inputStream: InputStream) {
            var numBytes: Int // bytes returned from read()
            // Keep listening to the InputStream until an exception occurs.
            while (true) {
                // Read from the InputStream.
                numBytes = try {
                    inputStream.read(mmBuffer)
                } catch (e: IOException) {
                    Log.d(TAG, "Input stream was disconnected", e)
                    break
                }
                // todo 读取到的数据的处理工作

            }
        }

        /****
         * 断开连接
         */
        fun cancel() {
            try {
                mmSocket?.close()
                //todo 断开连接成功
            } catch (e: IOException) {
                //todo 断开连接异常
            }
        }
    }
}








